
/**
 * Date:2019年5月30日下午5:25:41
 * Copyright (c) 2019, www.bwbroad.com All Rights Reserved.
 *
*/

package com.xue.im.client.handler;

import com.xue.im.client.core.IMClientContext;
import com.xue.im.common.IMUtil;
import com.xue.im.common.IMUtil.MessageType;
import com.xue.im.common.vo.Message;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * Description: TODO <br/>
 * Date: 2019年5月30日 下午5:25:41 <br/>
 * 
 * @author xuejianxin
 */
public class TextRequestHandler extends SimpleChannelInboundHandler<Object> {
	private ChannelHandlerContext chc = null;

	public TextRequestHandler() {
	}

	// 主动关闭连接
	public void closeChannel(boolean readyToClose) throws InterruptedException {
		if (readyToClose) {
			chc.channel().closeFuture();
			chc.channel().close();
		}
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		chc = ctx;
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
		Message message = (Message) msg;
		if (IMUtil.checkMessageType(message, MessageType.TEXT_RESP)
				|| IMUtil.checkMessageType(message, MessageType.USERLIST_RESP)
				|| IMUtil.checkMessageType(message, MessageType.USER_ONLIE_RESP)
				|| IMUtil.checkMessageType(message, MessageType.FILE_RESP)
				) {
			// 接收消息到消息队列
			IMClientContext.get().receiveMessage(message);
		} else {
			ctx.fireChannelRead(msg);
		}

	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		ctx.channel().closeFuture();
		ctx.channel().close();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.channel().close();
	}
}
